package http

import (
	"context"
	"fmt"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"server/component"
	"server/http/controller"
	"server/http/middleware"
	"time"
)

var httpServer Server

func Start() {
	httpServer.Start()
}

func Stop() {
	// 设置超时并关闭
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	if err := httpServer.http.Shutdown(ctx); err != nil {
		log.Fatal("强制关闭: ", err)
	}
	log.Println("服务已安全退出")
}

type Server struct {
	//http *gin.Engine
	http *http.Server
}

func (o *Server) Start() {

	router := gin.New()
	o.routes(router)

	port := component.ConfigModel.HttpServer.Port
	if port == "" {
		port = "8080"
	}

	httpServer.http = &http.Server{
		Addr:    ":" + port,
		Handler: router,
	}

	fmt.Println("http run at " + port)
	
	if err := httpServer.http.ListenAndServe(); err != nil && err != http.ErrServerClosed {
		log.Fatalf("服务启动失败: %v", err)
	}
}

func (o *Server) routes(router *gin.Engine) {

	router.Use(middleware.Logger())
	router.Use(gin.Recovery())

	router.LoadHTMLGlob("templates/*")
	router.Static("/public", "./public")

	router.Any("/ping", func(c *gin.Context) {
		c.String(http.StatusOK, "pong")
	})

	router.Any("/reg", controller.Reg)
	router.Any("/login", controller.Login)

	router.Any("/ws", func(c *gin.Context) {
		c.HTML(http.StatusOK, "ws.html", nil)
	})

	auth := router.Group("/").Use(middleware.Auth())
	{
		auth.Any("/change_pwd", controller.ChangePwd)
	}

}
